<style lang="scss" scoped>
.className {
  position: relative;
}
</style>
<template>
  <div class="className" :style="{ height: height, width: width }" />
</template>

<script>
import * as echarts from "echarts";
require("echarts/theme/macarons"); // echarts theme
import resize from "@/views/dashboard/mixins/resize";
import arrow_left_fill from "@/assets/images/dashboard/arrow_left_fill.png";
import arrow_right_fill from "@/assets/images/dashboard/arrow_right_fill.png";
import { booleanClockwise } from "@turf/turf";
// import graph from "../graph/graph";
var adata = 0;
var bdata = 0;
var debounceTimer = null; //定时器 鼠标滚动防抖
export default {
  mixins: [resize],
  props: {
    width: {
      type: String,
      default: "100%",
    },
    height: {
      type: String,
      default: "100%",
    },
    autoResize: {
      type: Boolean,
      default: true,
    },
    chartData: {
      type: Object,
      required: true,
    },
    startPoint: {
      type: Number,
      default: 0,
    },
    endPoint: {
      type: Number,
      default: 0,
    },
    tableData: {
      type: Array,
      default: function () {
        return [];
      },
    },
    startDis: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      chart: null,
      aLineLeft: 0, //a线
      bLineLeft: 0, //b线
      echartTableData: [], //table表的数据
      overAthousand: true, //x轴的显示 是否大于1000 , 大于是true
      midValPosi: 0, //缩放时候的中心点的点位
      aPoint: 0, //点击A按钮时候a点的点位
      bPoint: 0, //点击B按钮时候b点的点位
    };
  },
  watch: {
    startDis: {
      handler(val) {
        if (!val) {
          this.aLineLeft = 0;
          this.bLineLeft = 0;
          this.chart.clear();
        }
      },
    },
    chartData: {
      deep: true,
      handler(val) {
        // this.chart.clear();
        this.setOptions(val, true);
      },
      // immediate: true,
    },
    startPoint: {
      handler(val) {
        let that = this;
        that.setABlineFun();
        that.graphicFun(val);
      },
    },
    endPoint: {
      handler(val) {
        let that = this;
        that.setABlineFun();
        that.graphicFun(val);
      },
    },
    tableData: {
      handler(val) {
        let midArr = JSON.parse(JSON.stringify(val));
        let arr = midArr.filter((e) => {
          return e.type !== 9;
        });
        this.echartTableData = arr;
        this.graphicEvent(this.echartTableData);
      },
      deep: true,
    },
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart();
    });
  },
  beforeDestroy() {
    // if (!this.chart) {
    //   return;
    // }
    // this.chart.dispose();
    // this.chart = null;
  },
  methods: {
    initChart() {
      let that = this;
      that.chart = echarts.init(that.$el, "macarons");
      that.$nextTick(() => {
        that.setOptions(that.chartData);
        that.chart.on("click", function (params) {
          // 控制台打印数据的名称
          // 你可以在这里添加更多的逻辑处理
        });
      });
    },
    findClosestValueSorted(porp) {
      //计算是第多少个点位
      //获取与x值最近的值, 从而获取到y值
      let that = this;
      let target = porp * 1000;
      // console.log(target, "---------------", that.lineChartData);
      let arr = that.chartData.xData;
      if (!arr || arr.length === 0) return null; // 如果数组为空，返回 null
      let start = 0;
      let end = arr.length - 1;
      // 二分查找
      while (start <= end) {
        const mid = Math.floor((start + end) / 2);
        if (arr[mid] === target) {
          return arr[mid]; // 如果找到了目标值，直接返回
        } else if (arr[mid] < target) {
          start = mid + 1;
        } else {
          end = mid - 1;
        }
      }
      // 检查最近的两个候选值
      const closestStart = arr[end];
      const closestEnd = arr[start];
      // 返回与目标值最接近的值
      let targetVal = 0;
      if (end >= 0 && start < arr.length) {
        Math.abs(target - closestStart) <= Math.abs(closestEnd - target)
          ? (targetVal = closestStart)
          : (targetVal = closestEnd);
      } else if (end >= 0) {
        targetVal = closestStart;
      } else {
        targetVal = closestEnd;
      }
      let valIndex = 0;
      for (let i = 0; i < arr.length; i++) {
        if (arr[i] === targetVal) {
          return (valIndex = i);
        }
      }
    },

    graphicEvent(tableData) {
      //graphic 制作事件 图表
      let that = this;
      let graphic = [];
      tableData.map((item, index) => {
        let showValue = [];
        showValue = that.chart.convertToPixel({ seriesIndex: 0 }, [
          that.findClosestValueSorted(item.startDist),
          item.startLevel,
        ]);
        if (item.type == 1) {
          graphic.push({
            id: "image-start-top-" + index,
            type: "image", // 使用 image 元素
            style: {
              image: arrow_right_fill, // 图像的 URL
              width: 24, // 图像宽度
              height: 24, // 图像高度
              opacity: 1, // 透明度
              rotation: Math.PI / 4, // 旋转 45 度 (π/4 弧度)
            },
            x: showValue[0] - 4,
            y: showValue[1] - 22,
            z: 100, // 图层层级，确保图像位于其他元素之上
          });
          graphic.push({
            id: "image-start-bottom-" + index,
            type: "image", // 使用 image 元素
            style: {
              image: arrow_right_fill, // 图像的 URL
              width: 24, // 图像宽度
              height: 24, // 图像高度
              opacity: 1, // 透明度
              rotation: Math.PI / 4, // 旋转 45 度 (π/4 弧度)
            },
            // position: ["50%", "50%"], // 将图像放置在图表的中心
            x: showValue[0] - 4,
            y: showValue[1] - 2,
            z: 100, // 图层层级，确保图像位于其他元素之上
          });
        } else if (item.type == 2) {
          graphic.push({
            id: "image-end-top-" + index,
            type: "image", // 使用 image 元素
            style: {
              image: arrow_left_fill, // 图像的 URL
              width: 24, // 图像宽度
              height: 24, // 图像高度
              opacity: 1, // 透明度
              rotation: Math.PI / 4, // 旋转 45 度 (π/4 弧度)
            },
            // position: ["50%", "50%"], // 将图像放置在图表的中心
            x: showValue[0] - 20,
            y: showValue[1] - 2,
            z: 100, // 图层层级，确保图像位于其他元素之上
          });
          graphic.push({
            id: "image-end-bottom-" + index,
            type: "image", // 使用 image 元素
            style: {
              image: arrow_left_fill, // 图像的 URL
              width: 24, // 图像宽度
              height: 24, // 图像高度
              opacity: 1, // 透明度
              rotation: Math.PI / 4, // 旋转 45 度 (π/4 弧度)
            },
            // position: ["50%", "50%"], // 将图像放置在图表的中心
            x: showValue[0] - 20,
            y: showValue[1] - 22,
            z: 100, // 图层层级，确保图像位于其他元素之上
          });
        }
        graphic.push({
          id: "line-line_" + index,
          type: "line",
          x: showValue[0],
          textConfig: {
            position: "top",
            inside: true,
          },
          shape: {
            y1: showValue[1] + 10,
            y2: showValue[1] - 10, // 使用像素坐标
          },
          style: {
            stroke: "#f40",
            lineWidth: 1,
          },
        });
        graphic.push({
          id: "line-text_" + index,
          type: "text",
          x: showValue[0],
          style: {
            text: item.index, // 要显示的文字
            y: showValue[1] - 20, // 文字的 y 坐标，设置为圆心的 y 坐标
            // textAlign: "center", // 文字水平居中
            textVerticalAlign: "middle", // 文字垂直居中
            fill: "#f10", // 文字颜色
            font: "13px Arial", // 文字字体和大小
          },
        });
      });
      that.chart.setOption({
        graphic,
      });
    },
    setABlineFun() {
      //如果startPoint变了, 就换算a线的px值
      //如果endPoint变了, 就换算b线的px值
      let that = this;
      var startValue = that.chart.convertToPixel({ seriesIndex: 0 }, [
        that.startPoint,
        0,
      ]);
      that.aLineLeft = startValue[0]; //获取 AB线的初始值
      setTimeout(() => {
        that.pointDataFun(that.aLineLeft, 0, 1);
      }, 50);

      var endValue = [];
      //说明状态已经是el, end节点已经获取
      endValue = that.chart.convertToPixel({ seriesIndex: 0 }, [
        that.endPoint,
        0,
      ]);
      that.bLineLeft = endValue[0];
      setTimeout(() => {
        that.pointDataFun(that.bLineLeft, 9, 0);
      }, 50);
    },
    graphicFun() {
      //graphic 制作  AB线
      let that = this;
      const graphic = [];
      let arrMid = [1, 2];
      var startValue = that.chart.convertToPixel({ seriesIndex: 0 }, [
        that.startPoint,
        0,
      ]);
      var endValue = that.chart.convertToPixel({ seriesIndex: 0 }, [
        that.endPoint,
        0,
      ]);
      that.aLineLeft = startValue[0];
      that.bLineLeft = endValue[0];
      arrMid.map((item, index) => {
        graphic.push({
          type: "group",
          id: index + "-group",
          x: index === 1 ? startValue[0] : endValue[0],
          children: [
            {
              id: "line-" + index,
              type: "line",
              cursor: "move",
              textConfig: {
                position: "top",
                inside: true,
              },
              shape: {
                y1: 30,
                y2: that.chart.getHeight() - 30 - 10, // 使用像素坐标
              },
              style: {
                stroke: "#000",
                lineWidth: 1,
              },
            },
            {
              type: "circle",
              id: "circleMarker-" + index,
              top: index === 1 ? 80 : 130,
              cursor: "move",
              shape: {
                r: 18,
              },
              style: {
                fill: "#298CC4", // 不填充颜色
                stroke: index === 1 ? "#298CC4" : "#298CC4", // 边框颜色
                lineWidth: 2, // 边框宽度
              },
            },
            {
              type: "text",
              id: "text-" + index,
              style: {
                text: index === 1 ? "A" : "B", // 要显示的文字
                y: index === 1 ? 100 : 150, // 文字的 y 坐标，设置为圆心的 y 坐标
                textAlign: "center", // 文字水平居中
                textVerticalAlign: "middle", // 文字垂直居中
                fill: "#fff", // 文字颜色
                font: "16px Arial", // 文字字体和大小
              },
            },
            {
              id: "rect-" + index,
              type: "rect", // 创建背景矩形
              shape: {
                width: 100,
                height: 40,
              },
              style: {
                fill: "rgba(0,0,0,0.7)", // 背景颜色
                stroke: "#000", // 边框颜色
                lineWidth: 1,
              },
              y: index === 1 ? 30 : 80, // 文字的 y 坐标，设置为圆心的 y 坐标
              left: "center", // 初始位置
              z: 100, // 确保矩形位于最上层
            },
            {
              id: "rect-text-top-" + index,
              type: "text", // 创建文本
              style: {
                text: "", // 初始文本为空
                fontSize: 13,
                fill: "#fff", // 文字颜色
                textAlign: "left", // 文字水平居中
                textVerticalAlign: "middle", // 文字垂直居中
                textBaseline: "top", // 基线对齐方式
              },
              left: -45, // 文本居中
              y: index === 1 ? 50 - 9 : 100 - 9, // 文字的 y 坐标，设置为圆心的 y 坐标
              z: 101, // 确保文本位于矩形之上
            },
            {
              id: "rect-text-bottom-" + index,
              type: "text", // 创建文本
              style: {
                text: "", // 初始文本为空
                fontSize: 13,
                fill: "#fff", // 文字颜色
                textAlign: "left", // 文字水平居中
                textVerticalAlign: "middle", // 文字垂直居中
                textBaseline: "top", // 基线对齐方式
              },
              left: -45, // 文本居中
              y: index === 1 ? 50 + 9 : 100 + 9, // 文字的 y 坐标，设置为圆心的 y 坐标
              z: 101, // 确保文本位于矩形之上
            },
          ],
          draggable: true, // 设置整个group可拖拽
          ondrag: function (params, event) {
            that.limitedRegionMove(params, index);
            // 直接在画布坐标系上进行操作，不需要转换
            // params.target.shape.x1 = params.target.shape.x2 = params.offsetX;
            // that.chart.setOption({ graphic });
          },
          ondragend: function (params, event) {
            // console.log("params, event", params, event);
            that.onDragend(index, params);
          },
        });
      });
      that.chart.setOption({
        graphic,
      });
    },
    calcABPointsFun() {
      //计算Ab点位的 值
      let that = this;
      // 获取 X 轴上的两个相邻数据点的索引
      const dataIndex1 = 0; // 第一个点的索引
      const dataIndex2 = 1; // 第二个点的索引
      // 获取 X 轴的值（假设 X 轴是类别轴，dataIndex 对应的是类别的索引）
      const xAxisValue1 = that.chart
        .getModel()
        .getSeriesByIndex(0)
        .getData()
        .getName(dataIndex1);
      const xAxisValue2 = that.chart
        .getModel()
        .getSeriesByIndex(0)
        .getData()
        .getName(dataIndex2);
      // 将 X 轴的值转换为像素坐标
      const point1 = that.chart.convertToPixel({ seriesIndex: 0 }, [
        xAxisValue1,
        null,
      ]);
      const point2 = that.chart.convertToPixel({ seriesIndex: 0 }, [
        xAxisValue2,
        null,
      ]);

      // 计算两个点之间的像素距离
      const distance = Math.abs(point2[0] - point1[0]);
      let aNum = parseInt(10 / distance);
      that.aPoint = that.midValPosi - aNum;
      let bNum = parseInt(56 / distance);
      that.bPoint = that.midValPosi + bNum;
    },
    setOptions({ seriesData, xData }) {
      let that = this;
      that.chart.setOption(
        {
          xAxis: {
            name: "长度",
            type: "category",
            data: xData,
            axisLabel: {
              formatter: function (value) {
                var intValue = Math.round(value);
                let showVal = 0;
                if (value && value != "0" && value.length > 0) {
                  showVal = intValue?.toFixed(0);
                }
                let showText = "";
                if (showVal > 1000) {
                  showText = showVal / 1000 + "km";
                } else {
                  showText = showVal + "m";
                }
                return showText;
              },
              splitNumber: 400,
              // interval: 600, // 显示的标签
            },
            // axisLine: {
            //   lineStyle: {
            //     color: "#298CC4",
            //   },
            // },
            splitLine: {
              show: true, // 显示 X 轴的分割线
              lineStyle: {
                color: "#dfe6ec", // 分割线颜色
                width: 1,
                type: "dashed", // 分割线类型（实线或虚线）
              },
            },
            axisLine: {
              show: true, // 显示 Y 轴线
              lineStyle: {
                color: "#333", // Y 轴线的颜色
                width: 1, // Y 轴线的宽度
                type: "solid", // Y 轴线的类型（实线或虚线）
              },
            },
          },
          yAxis: {
            axisTick: {
              show: false,
            },
            axisLine: {
              show: true, // 显示 Y 轴线
              lineStyle: {
                color: "#333", // Y 轴线的颜色
                width: 1, // Y 轴线的宽度
                type: "solid", // Y 轴线的类型（实线或虚线）
              },
            },
            splitArea: false,
            type: "value",
            min: 0,
            max: 60,
            splitLine: {
              show: true, // 显示 Y 轴的分割线
              lineStyle: {
                color: "#dfe6ec", // 分割线颜色
                width: 1,
                type: "dashed", // 分割线类型（实线或虚线）
              },
            },
          },
          grid: {
            left: 10,
            right: 10,
            bottom: 20,
            top: 30,
            containLabel: true,
          },
          dataZoom: [
            // {
            //   type: "inside",
            //   zoomOnMouseWheel: true, // 启用滚轮缩放
            //   moveOnMouseMove: true, // 启用鼠标移动时平移
            //   moveOnTouchMove: true, // 启用触摸屏上的平移
            // },
            {
              type: "inside", // 内置型 dataZoom
              // start: 0, // 初始起始百分比
              // end: 60, // 初始结束百分比
              minSpan: 1, // 最小缩放范围为 10%
              maxSpan: 97, // 最大缩放范围为 80%
            },
          ],
          tooltip: {
            show: false,
            // trigger: "axis",
            // axisPointer: {
            //   type: "cross",
            //   show: true,
            // },
            // padding: [5, 10],
          },
          series: [
            {
              name: "衰耗",
              symbol: "none",
              itemStyle: {
                normal: {
                  lineStyle: {
                    color: "#1E79BA",
                    width: 1,
                  },
                },
              },
              type: "line",
              data: seriesData,
            },
          ],
        },
        true
      );
      that.chart.on("dataZoom", function (params) {
        // 清除之前的计时器
        clearTimeout(debounceTimer);
        // 重新设置计时器，等待 200 毫秒后执行回调函数
        debounceTimer = setTimeout(function () {
          // console.log("params", params);
          if (params?.start === 0 && params?.end === 100) {
            //说明是原始的缩放比例
            that.$parent.dataZoomFun(true);
          } else {
            //说明可以点击 返回原始比例缩放按钮
            that.$parent.dataZoomFun(false);
          }
          // 在这里执行你操作，更新 UI
          that.graphicEvent(that.echartTableData);
          that.graphicFun();
          that.pointDataFun(that.aLineLeft, 0, 1);
          that.pointDataFun(that.bLineLeft, 9, 0);
          that.getXposition(params.batch[0].start, params.batch[0].end); //
          that.calcABPointsFun();
        }, 150); // 200 毫秒的延迟
      });
    },
    getXposition(start, end) {
      //放大缩小之后, 可以获取到 起点和终点的百分比 , 根据百分比计算出起点和终点
      let that = this;
      let length = that.chartData.xData.length;
      let startpercentPoint = Math.floor((start / 100) * length);
      let endpercentPoint = Math.floor((end / 100) * length);
      let startValuePosiont = that.chartData.xData[startpercentPoint];
      let endValuePosiont = that.chartData.xData[endpercentPoint - 1];

      let midPercentPoint = (start + end) / 2;
      that.midValPosi = Math.floor((midPercentPoint / 100) * length);

      //需要设置A B两个按钮, 如果缩放图表之后, A或者B线不在图标显示范围内 , 就需要显示对应的按钮, 然后点击按钮后,可以显示对应的线
      let aValue = that.chartData.xData[that.startPoint];
      let bValue = that.chartData.xData[that.endPoint];
      if (endValuePosiont > startValuePosiont) {
        //B线在A线的右侧
        if (aValue < endValuePosiont && aValue >= startValuePosiont) {
          //A线在范围内
          that.$parent.ablineFun("a", true);
        } else {
          //A线不在范围内
          that.$parent.ablineFun("a", false);
        }
        if (bValue < endValuePosiont && bValue >= startValuePosiont) {
          //B线在范围内
          that.$parent.ablineFun("b", true);
        } else {
          //B线不在范围内
          that.$parent.ablineFun("b", false);
        }
      } else if (endValuePosiont === startValuePosiont) {
        //两线在一起
      } else {
        //B线在A线左侧
        if (aValue < startValuePosiont && aValue >= endValuePosiont) {
          //A线在范围内
          that.$parent.ablineFun("a", true);
        } else {
          //A线不在范围内
          that.$parent.ablineFun("a", false);
        }
        if (bValue < startValuePosiont && bValue >= endValuePosiont) {
          //B线在范围内
          that.$parent.ablineFun("b", true);
        } else {
          ///B线不在范围内
          that.$parent.ablineFun("b", false);
        }
      }
      // 需要计算 整个x轴的距离, 如果小于一公里, 就需要显示m, 否则显示km
      let subtractionValue = endValuePosiont - startValuePosiont;
      if (subtractionValue - 1000 > 0) {
        that.startFun();
      } else {
        that.overAthousand = false;
        that.chart.setOption({
          xAxis: [
            {
              // data: currentXAxisData,
              axisLabel: {
                formatter: function (value) {
                  let showText = "";
                  let midStr = value.split(".");
                  showText = midStr[0];
                  return showText + "m";
                },
                splitNumber: 10,
              },
            },
          ],
        });
      }
    },
    //grid距离边界的距离
    getGridDistance: function (direction) {
      let grid = this.chart.getOption().grid[0],
        gridWidth = this.chart.getWidth(), //ECharts 实例容器的宽度
        gridHeight = this.chart.getHeight(), //ECharts 实例容器的高度
        distance = 0;

      //若是百分数长度转化成数值型长度
      //由于线宽的影响，计算游标位置时将游标位置向左偏移2px，向下偏移2px
      switch (direction) {
        case "left":
          // distance = grid.left; //grid距离左边边界的距离
          // let index = distance.toString().indexOf("%");
          // distance =
          //   index == -1
          //     ? distance - 2
          //     : (distance.substring(0, index) * gridWidth) / 100 - 2;
          distance = 31;
          break;
        case "right":
          distance = grid.right; //grid距离右边边界的距离
          let indexr = distance.toString().indexOf("%");
          distance =
            indexr == -1
              ? distance + 2
              : (distance.substring(0, indexr) * gridWidth) / 100 + 2;
          break;
        case "top":
          distance = grid.top;
          let indext = distance.toString().indexOf("%");
          distance =
            indext == -1
              ? distance + 2
              : (distance.substring(0, indext) * gridHeight) / 100 + 2;
          break;
        case "bottom":
          distance = 38;
          break;
        default:
          console.log("default grid距离边界的距离");
          break;
      }
      return distance;
    },
    showTextFun(e) {
      //显示 a b的文字
      let showNum = 0;
      if (e == 0) {
        return 0 + "m";
      } else if (!e) {
        return (e?.toFixed(2) || 0) + "m";
      } else if (!this.overAthousand) {
        //小于1000
        return (e?.toFixed(2) || 0) + "m";
      } else {
        //大于1000
        showNum = e / 1000;
        return (showNum?.toFixed(3) || 0) + "km";
      }
    },
    pointDataFun(x, y, index) {
      // 将像素坐标转换为数据坐标 , 然后展示出 当前的x 和 y的 文字值
      let that = this;
      var pointInData = that.chart.convertFromPixel({ seriesIndex: 0 }, [x, y]);
      var xValue = pointInData[0];
      let showXtext = that.chartData.xData[xValue];
      let showYtext = that.chartData.seriesData[xValue];
      let graphic = {};
      if (index === 1) {
        //是A线
        graphic = [
          {
            id: "rect-text-top-1",
            style: {
              text: `x: ${that.showTextFun(showXtext) || 0}`,
            },
          },
          {
            id: "rect-text-bottom-1",
            style: {
              text: `y: ${showYtext || 0}dB`,
            },
          },
        ];
      } else {
        graphic = [
          {
            id: "rect-text-top-0",
            style: {
              text: `x: ${that.showTextFun(showXtext) || 0}`,
            },
          },
          {
            id: "rect-text-bottom-0",
            style: {
              text: `y: ${showYtext || 0}dB`,
            },
          },
        ];
      }
      that.chart.setOption({ graphic });
    },
    //限制鼠标移动区域
    limitedRegionMove: function (e, index) {
      //index  1是A   0是B
      //获取 AB线的 位置      // 从配置项中获取graphic组件的信息
      let that = this;
      let x = e.offsetX,
        y = e.offsetY,
        letfX = x,
        gridWidth = that.chart.getWidth(),
        minX = that.getGridDistance("left"),
        maxX = gridWidth - that.getGridDistance("right"),
        gridBottom = that.getGridDistance("bottom");
      let tempY = 0; //临时存放y值
      //判断A  B线的位置,  A永远在B的左面
      var currentOption = that.chart.getOption();
      var graphics = currentOption.graphic;
      let elements = graphics[0].elements;
      if (letfX <= minX) {
        letfX = minX;
      }
      if (index === 0) {
        //移动的是B线
        that.bLineLeft = letfX;
      }
      if (index === 1) {
        //移动的是a线
        that.aLineLeft = letfX;
      }
      //展示当前的x 和 y的值 , 在AB线 上显示
      that.pointDataFun(x, y, index);
      // if (that.aLineLeft > that.bLineLeft) {
      //   let id = e.target.id; //获取游标的id
      //   if (index === 1) {
      //     //是A线
      //     letfX = that.bLineLeft;
      //   } else {
      //     letfX = that.aLineLeft;
      //   }
      //   let graphic = {
      //     id: id,
      //     x: letfX,
      //   };
      //   that.chart.setOption({ graphic });
      // }
      //上下不允许拖动，左右设定移动范围
      if (x <= minX || x > maxX || Math.abs(y - tempY) > 0) {
        let id = e.target.id; //获取游标的id
        tempY = y; //鼠标拖动前一次y轴值
        if (x <= minX) {
          letfX = minX;
        } else if (x > maxX) {
          letfX = maxX;
        }
        let graphic = {
          id: id,
          x: letfX,
          bottom: gridBottom,
        };
        that.chart.setOption({ graphic });
      }
      if (index === 1) {
        //要根据拖动  与地图联动
      }
    },
    // 拖拽完渲染
    onDragend(index, param) {
      let that = this;
      let letfX = param.offsetX;
      let id = param.target.id; //获取游标的id
      let minX = that.getGridDistance("left");
      let gridWidth = that.chart.getWidth();
      let maxX = gridWidth - that.getGridDistance("right");
      if (letfX <= minX) {
        letfX = minX;
      }
      if (letfX >= maxX) {
        letfX = maxX;
      }
      //判断A  B线的位置,  A永远在B的左面
      // if (that.aLineLeft > that.bLineLeft) {
      //   if (index === 1) {
      //     //是A线
      //     letfX = that.bLineLeft;
      //   } else {
      //     letfX = that.aLineLeft;
      //   }
      // }
      let graphic = {
        id: id,
        x: letfX,
      };
      that.chart.setOption({ graphic });
      var xValue = that.convertFromPixel(param.offsetX);
      if (param.offsetX <= minX) {
        //如果 小于了最小值, 出了边框
        xValue = that.convertFromPixel(minX);
      }
      if (param.offsetX >= maxX) {
        //如果大于了 最大值,  出了边框
        xValue = that.convertFromPixel(maxX);
      }
      //index  1是A   0是B
      //获取 AB线的 位置
      // 从配置项中获取graphic组件的信息
      var currentOption = that.chart.getOption();
      var graphics = currentOption.graphic;
      let elements = graphics[0].elements;
      let aIndex = 0;
      let bIndex = 1;
      for (let i = 0; i < elements.length; i++) {
        //获取到 AB线在 graphic中的索引位置
        if (
          elements[i].type === "group" &&
          (elements[i].x || elements[i] == 0)
        ) {
          if (elements[i].id === "0-group") {
            bIndex = i;
          }
          if (elements[i].id === "1-group") {
            aIndex = i;
          }
        }
      }
      //index  1是A   0是B
      if (index == "1") {
        //A线
        let distance = this.chartData.xData[xValue];
        that.$parent.getGisPosition(distance / 1000); //这个要的是 km的距离
        adata = xValue;
        bdata = that.convertFromPixel(graphics[0].elements[bIndex].x);
      } else {
        //B线
        bdata = xValue; //获取x轴的 第多少少个点位
        adata = that.convertFromPixel(graphics[0].elements[aIndex].x);
      }
      this.$parent.abCalcFun(adata, bdata);
    },
    convertFromPixel(offsetX) {
      //根据x的left值,  , 计算是x轴上的第多少个点位
      var xValue = this.chart.convertFromPixel({ seriesIndex: 0 }, [
        offsetX,
        0,
      ]);
      return xValue[0];
    },
    recoveryRatio() {
      //重置缩放比例
      this.chart.dispatchAction({
        type: "dataZoom",
        start: 0,
        end: 100,
        componentType: "dataZoom",
      });
    },
    startFun() {
      //点击测试, 需要重新赋值 ab线显示的文字
      let that = this;
      that.overAthousand = true;
      that.chart.setOption({
        xAxis: [
          {
            axisLabel: {
              formatter: function (value) {
                var intValue = Math.round(value);
                let showVal = 0;
                if (value && value != "0" && value.length > 0) {
                  showVal = intValue?.toFixed(0);
                }
                let showText = "";
                if (showVal > 1000) {
                  showText = showVal / 1000 + "km";
                } else {
                  showText = showVal + "m";
                }
                return showText;
              },
              splitNumber: 400,
              // interval: 600, // 显示的标签
            },
          },
        ],
      });
    },
  },
};
</script>
